package com.morningstar.flow.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.morningstar.flow.dao.entity.FlowInstance;
import com.morningstar.flow.dao.entity.FlowNodeCopy;
import com.morningstar.flow.dao.mapper.FlowNodeCopyMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class FlowNodeCopyService extends ServiceImpl<FlowNodeCopyMapper, FlowNodeCopy> {

    @Resource
    private FlowNodeCopyMapper flowNodeCopyMapper;

    @Resource
    private FlowInstanceTimeLineService flowInstanceTimeLineService;

    /**
     * 抄送我的查询
     *
     * @param page 分页参数
     * @return 分页参数
     */
    public IPage<FlowInstance> copyList(IPage<FlowInstance> page, FlowNodeCopy flowNodeCopy) {
        return flowNodeCopyMapper.copyList(page, flowNodeCopy);
    }

    /**
     * 抄送节点
     *
     * @param userIds 用户Id列表
     * @param entity  执行实例列表
     */
    @Transactional(rollbackFor = Exception.class)
    public void processCopy(Set<Long> userIds, ExecutionEntityImpl entity) {
        LambdaQueryWrapper<FlowNodeCopy> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FlowNodeCopy::getProcessInstanceId, entity.getProcessInstanceId());
        List<Long> oldUserIds = flowNodeCopyMapper.selectList(wrapper).stream().map(FlowNodeCopy::getUserId).toList();
        oldUserIds.forEach(userIds::remove);
        List<FlowNodeCopy> list = new ArrayList<>();
        for (Long userId : userIds) {
            FlowNodeCopy flowNodeCopy = FlowNodeCopy.builder()
                    .processInstanceId(entity.getProcessInstanceId())
                    .nodeActivityId(entity.getActivityId())
                    .userId(userId)
                    .createTime(LocalDateTime.now())
                    .build();
            list.add(flowNodeCopy);
        }
        this.saveBatch(list);
        flowInstanceTimeLineService.taskCopy(entity, -99999L, "抄送节点");
    }

}
